package com.dong.mcd.service.impl;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.dong.mcd.dao.SysMenuMapper;
import com.dong.mcd.model.SysMenu;
import com.dong.mcd.model.SysMenuExample;
import com.dong.mcd.model.SysMenuExample.Criteria;
import com.dong.mcd.param.SysMenuParam;
import com.dong.mcd.service.IMenuService;
import com.dong.mcd.util.PageConfig;

@Transactional
@Service("menuService")
public class MenuServiceImpl implements IMenuService {
	
	@Autowired
	private SysMenuMapper menuMapper;
	
	public void addMenu(SysMenu menu) {
		menu.setCreateDate(new Date());
		menuMapper.insert(menu);
	}

	public void modifyMenu(SysMenu menu) {
		menuMapper.updateByPrimaryKeySelective(menu);
	}

	public List<SysMenu> query(SysMenuParam param) {
		//查询条件
		SysMenuExample example = new SysMenuExample();
		Criteria criteria = example.createCriteria();
		if (param.getOnlyParent() !=null && param.getOnlyParent().equals("1"))
			criteria.andParentIdIsNull();
		if (param.getOnlyParent() !=null && param.getOnlyParent().equals("0"))
			criteria.andParentIdIsNotNull();
		if (StringUtils.isNotEmpty(param.getId()))
			criteria.andIdLike("%"+param.getId()+"%");
		if (StringUtils.isNotEmpty(param.getName())) 
			criteria.andNameLike("%"+param.getName()+"%");
		if (StringUtils.isNotEmpty(param.getParentId()))
			criteria.andParentIdEqualTo(param.getParentId());
		example.setOrderByClause("parent_id,seq");
		return menuMapper.selectByExample(example);
	}

	public PageConfig queryPage(SysMenuParam param, Integer pageIndex,
			Integer pageSize) {
		//查询条件
		SysMenuExample example = new SysMenuExample();
		Criteria criteria = example.createCriteria();
		if (StringUtils.isNotEmpty(param.getId()))
			criteria.andIdLike("%"+param.getId()+"%");
		if (StringUtils.isNotEmpty(param.getName()))
			criteria.andNameLike("%"+param.getName()+"%");
		if (StringUtils.isNotEmpty(param.getParentId()))
			criteria.andParentIdEqualTo(param.getParentId());
		example.setOrderByClause("parent_id,seq");
		return new PageConfig(menuMapper,example,pageIndex,pageSize);
	}

	public void removeMenu(String id) {
			menuMapper.deleteByPrimaryKey(id);
	}

	public SysMenu getMenuById(String id) {
		return menuMapper.selectByPrimaryKey(id);
	}

	public List<SysMenu> getUserMenus(Integer userId) {
		return menuMapper.getUserMenus(userId);
	}

	public List<SysMenu> getRoleMenusAll(Integer roleId) {
		return menuMapper.getRoleMenusAll(roleId);
	}

}
